package com.mtao.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mtao.dto.WxDto;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Getter
@Setter
@Component
public class WxUtil {
    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;


    /**
     * 获取access_token
     * @return
     */
    public String getAccessToken() {
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        WebClient client = WebClient.create();
        Mono<String> result = client.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class);
        String block = result.block();
        // access_token expires_in
        JSONObject jsonObject = JSON.parseObject(block);
        String accessToken = jsonObject.getString("access_token");
        return accessToken;
    }

    public String getOpenId(WxDto wxDto) {
        String code=wxDto.getCode();
        String url="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        WebClient client = WebClient.create();
        Mono<String> result = client.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class);
        String block = result.block();
        System.out.println(block);
        JSONObject jsonObject = JSON.parseObject(block);
        String openId = jsonObject.getString("openid");
        return openId;
    }

}
